/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package elaborate.h2x.parser;

import elaborate.h2x.transform.Def;
import elaborate.h2x.transform.DefaultDefImpl;
import elaborate.h2x.transform.TransformingModel;
import elaborate.h2x.transform.TransformingNode;
import elaborate.h2x.transform.service.Services;
import java.util.ArrayList;
import java.util.List;
import org.w3c.dom.Attr;
import org.w3c.dom.Element;

/**
 *
 * @author lendle
 */
public class DefaultDefFactoryImpl implements DefFactory{

    public void createDef(Services services, TransformingModel model, TransformingNode node) throws ParserException {
        Element element=(Element) node.getOriginalNode();
        Attr defAttr = element.getAttributeNodeNS("h2x", "def");
        String defAttrValue=defAttr.getValue();
        if(defAttrValue==null || defAttrValue.length()==0){
            throw new ParserException("empty def setting");
        }
        String [] defs=defAttrValue.split(";");
        if(defs==null || defs.length==0){
            throw new ParserException("empty def setting");
        }
        for(String defSetting : defs){
            DefaultDefImpl def=new DefaultDefImpl();
            def.setDefExp(defSetting);
            
            String [] array=defSetting.split(",");
            if(array==null || array.length==0){
                throw new ParserException("error def setting: "+defSetting);
            }
            else if(array.length==1){
                this.parse(array[0], def, services, model, node, element);
            }
            else if(array.length==2){
                this.parse(array[0], array[1], def, services, model, node, element);
            }
        }
    }

    protected DefaultDefImpl parse(String target, String def_exp, DefaultDefImpl def, Services services, TransformingModel model, TransformingNode node, Element element){
        TransformingNode targetNode=services.getLocator().locateNode(model, node, target);
        return this.parse(targetNode, def_exp, def, services, model, node, element);
    }
    
    protected DefaultDefImpl parse(String def_exp, DefaultDefImpl def, Services services, TransformingModel model, TransformingNode node, Element element){
        return this.parse(node, def_exp, def, services, model, node, element);
    }
    
    protected DefaultDefImpl parse(TransformingNode target, String def_exp, DefaultDefImpl def, Services services, TransformingModel model, TransformingNode node, Element element){
        def.setDefExp(def_exp);
        def.setTarget(target.getId());
        target.setDef(def);
        //System.out.println(target.getOriginalNode().getNodeName()+":"+target.getOriginalNode().getNodeValue());
        //so we can have the list of nodes that will be included in the transformation result
        target.setIncludedInResult(true);
        def.setNode(services.getNodeGenerator().createNode(model, target, def_exp));
        return def;
    }
}
